package com.alibaba.citrus.ots.platform.enhance.facade.service.employee;

import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.sales.plan.model.enums.NickTypeEnum;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.cz.base.tool.trace.TraceUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.CreateAccountForTheFirstTimeRequest;
import com.epoch.app.bcots.model.dto.CreateAccountForTheFirstTimeResponse;
import com.epoch.app.bcots.model.dto.EmployeeGetCurrentLoginResponse;
import com.epoch.app.bcots.model.dto.RoleSDO;
import com.epoch.app.bcots.service.BcOtsService;
import com.epoch.app.otsplatformenhance.api.employeewrite.dto.CheckEmployeeRequest;
import com.epoch.app.otsplatformenhance.api.employeewrite.dto.ImportEmployeeHandleRequest;
import com.epoch.app.otsplatformenhance.api.employeewrite.service.EmployeeWriteService;
import com.epoch.app.otsplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.otsplatformenhance.contants.OtsPlatformEnhanceConstants;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.BatchQueryAddressByConditionRequest;
import com.epoch.app.otsplatformenhance.domain.customeraddress.model.CustomerAddress;
import com.epoch.app.otsplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.epoch.app.otsplatformenhance.dto.request.EmployeeImportRequest;
import com.epoch.app.otsplatformenhance.dto.request.IdQueryRequest;
import com.epoch.app.otsplatformenhance.dto.request.ImportRequest;
import com.epoch.app.otsplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.otsplatformenhance.model.dto.*;
import com.epoch.app.otsplatformenhance.sdo.EmployeeFullSDO;
import com.epoch.app.otsplatformenhance.sdo.EmployeeSDO;
import com.epoch.app.otsplatformenhance.sdo.OrganizationSDO;
import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:suqing.tjf
 * @date:2021/11/12
 */
@Component
public class EmployeeWriteServiceImpl implements EmployeeWriteService {

    private static final Log log = Log.getLogger(EmployeeWriteServiceImpl.class);

    @Resource
    private OtsPlatformEnhanceService otsPlatformEnhanceService;

    @Resource
    private BcOtsService bcOtsService;

    @Resource
    private OrganizationQueryService organizationQueryService;

    @Resource
    private CustomerAddressService customerAddressService;

    private static final String password = "mn-12345";

    //校验大小写英文字母和汉字
    private static final String regex1 = "^[a-zA-Z\\u4e00-\\u9fa5]+$";
    //校验大小写英文字母、汉字和下划线
    private static final String regex2 = "^[a-zA-Z0-9\\u4E00-\\u9FA5_]+$";
    //员工扩展字段中的标
    private final static String CUSTOMER_CODE = "customerCode";
    private final static String CUSTOMER_ADDRESS_CODE = "customerAddressCode";
    private final static String NICK_TYPE = "nickType";
    private final static String SUPERVISOR_NAME = "supervisorName";
    private final static String SUPERVISOR_WORK_ID = "supervisorWorkId";

    /**
     * importEmployeeHandle
     *
     * @param importEmployeeHandleRequest
     */
    @Override
    @FacadeInvoker
    public Result<List<EmployeeImportRequest>> importEmployeeHandle(ImportEmployeeHandleRequest importEmployeeHandleRequest) {
        log.info("EmployeeWriteServiceImpl.importEmployeeHandle:员工导入开始");
        List<EmployeeImportRequest> request = importEmployeeHandleRequest.getImportEmployeeHandleRequest();
        if (CollectionUtils.isEmpty(request)) {
            return Result.success(Lists.newArrayList());
        }
        ApiContext apiContext = importEmployeeHandleRequest.getApiContext();
        log.info("EmployeeWriteServiceImpl.importEmployeeHandle:apiContext={}", JSONObject.toJSONString(apiContext));
        if (apiContext == null) {
            setRequestErrorMessage(request, ErrorMessage.code("OTS-01-001-01-16-026", null).getDisplayErrorMessage());
            return Result.success(request);
        }
        //校验当前登陆员工权限
        log.info("EmployeeWriteServiceImpl.importEmployeeHandle:校验当前登陆员工权限");
        String relatedOrganizationId = apiContext.getRelatedOrganizationId();
        if (Strings.isBlank(relatedOrganizationId) || Strings.isBlank(apiContext.getRelatedOrganizationType())) {
            setRequestErrorMessage(request, ErrorMessage.code("OTS-01-001-01-16-025", null).getDisplayErrorMessage());
            return Result.success(request);
        }
        //查询当前登陆员工所在组织及下属组织
        IdQueryRequest idQueryRequest = new IdQueryRequest();
        idQueryRequest.setId(relatedOrganizationId);
        idQueryRequest.setType(106);
        Result<List<OrganizationSDO>> childOrganizationList = organizationQueryService.getAllChildOrganizationList(idQueryRequest);
        log.info("EmployeeWriteServiceImpl.importEmployeeHandle:查询当前登陆员工所在组织及下属组织={}", JSONObject.toJSONString(childOrganizationList));
        List<OrganizationSDO> organizationList = childOrganizationList.getResult();
        if (!childOrganizationList.isSuccess() || CollectionUtils.isEmpty(organizationList)) {
            setRequestErrorMessage(request, ErrorMessage.code("OTS-01-001-01-16-025", null).getDisplayErrorMessage());
            return Result.success(request);
        }
        Map<Optional<String>, OrganizationSDO> organizationSDOMap = organizationList.stream().collect(Collectors.toMap(organizationSDO -> Optional.ofNullable(organizationSDO.getCode()), o -> o));
        //入参必填校验：姓名、账号、手机号、所属组织编码、工号
        for (EmployeeImportRequest employeeRequest : request) {
            log.info("EmployeeWriteServiceImpl.importEmployeeHandle:employeeRequest={}", JSONObject.toJSONString(employeeRequest));
            try {
                log.info("EmployeeWriteServiceImpl.importEmployeeHandle:入参必填校验开始");
                //去除空格
                if (!trimBean(employeeRequest)) {
                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-021", null).getDisplayErrorMessage());
                    continue;
                }
                log.info("EmployeeWriteServiceImpl.importEmployeeHandle:去除空格");
                if (Strings.isBlank(employeeRequest.getWorkId())) {
                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-030", null).getDisplayErrorMessage());
                    continue;
                }
                if (Strings.isBlank(employeeRequest.getName())) {
                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-001", null).getDisplayErrorMessage());
                    continue;
                }
                if (!employeeRequest.getName().matches(regex1)) {
                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-022", null).getDisplayErrorMessage());
                    continue;
                }
                if (Strings.isBlank(employeeRequest.getNick())) {
                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-002", null).getDisplayErrorMessage());
                    continue;
//                    employeeRequest.setNick(employeeRequest.getWorkId());
                }
                if (!employeeRequest.getNick().matches(regex2)) {
                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-023", null).getDisplayErrorMessage());
                    continue;
                }
                if (Strings.isBlank(employeeRequest.getPhone())) {
                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-003", null).getDisplayErrorMessage());
                    continue;
                }
                if (Strings.isBlank(employeeRequest.getOrganizationCode())) {
                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-004", null).getDisplayErrorMessage());
                    continue;
                }
                if (Strings.isBlank(employeeRequest.getIdentityCardNumber())) {
                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-031", null).getDisplayErrorMessage());
                    continue;
                }

                //校验导入数据是否属于当前登陆员工的组织
                //根据组织编码获取组织id
//                List<OrganizationSDO> organizationList = otsPlatformEnhanceService.enhanceGetAllOrganization().getResult()
//                        .stream().filter(organizationSDO -> Strings.isNotBlank(organizationSDO.getCode())).collect(Collectors.toList());//获取所有组织
                OrganizationSDO organizationSDO = organizationSDOMap.get(Optional.ofNullable(employeeRequest.getOrganizationCode()));
                if (ObjectUtils.isEmpty(organizationSDO)) {
                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-027", null).getDisplayErrorMessage());
                    continue;
                }
                log.info("EmployeeWriteServiceImpl.importEmployeeHandle:入参必填校验结束");
                //需要新增的组织id(一个员工只能关联一个组织)
                employeeRequest.setRelationOrganizationId(organizationSDO.getId());
                //所属组织都是1
                employeeRequest.setBelongOrganizationId("1");
                //features里打标：customerCode、nickType、supervisorName、supervisorWorkId
                Map<String, String> featuresMap = convertFeaturesMap(employeeRequest);

                //根据账号判断员工是否已存在，新增的先创建员工（接口会返回id）,再关联组织，最后更新角色，已存在的员工更新信息和组织后再更新角色
                Result<List<EmployeeSDO>> employeeSDOList = otsPlatformEnhanceService.queryEmployees(QueryEmployeesRequest.builder()
                        .nick(employeeRequest.getNick()).build());//查询员工
                log.info("EmployeeWriteServiceImpl.importEmployeeHandle:查询员工是否已存在={}", JSONObject.toJSONString(employeeSDOList));
                if (CollectionUtils.isEmpty(employeeSDOList.getResult())) {
                    //需要新增的员工
                    log.info("初始密码:" + OtsPlatformEnhanceConstants.EMPLOYEE_PASSWORD());
                    CreateEmployeeResponse employee = otsPlatformEnhanceService.createEmployee(EmployeeFullSDO.builder()
                            .name(Optional.ofNullable(employeeRequest.getName()).orElse(null))
                            .nick(Optional.ofNullable(employeeRequest.getNick()).orElse(null))
                            .workId(Optional.ofNullable(employeeRequest.getWorkId()).orElse(null))
                            .phone(Optional.ofNullable(employeeRequest.getPhone()).orElse(null))
                            .email(Optional.ofNullable(employeeRequest.getEmail()).orElse(null))
                            .belongOrganizationId(Optional.ofNullable(employeeRequest.getBelongOrganizationId()).orElse(null))
                            .validStartDate(Optional.ofNullable(employeeRequest.getValidStartDate()).orElse(null))
                            .validEndDate(Optional.ofNullable(employeeRequest.getValidEndDate()).orElse(null))
                            .password(OtsPlatformEnhanceConstants.EMPLOYEE_PASSWORD())
                            .features(Optional.of(JSONObject.toJSONString(featuresMap)).orElse(null))
                            .identityCardNumber(Optional.of(employeeRequest.getIdentityCardNumber()).orElse(null))
                            .build());//创建员工
                    if (!employee.getSuccess() || employee.getId() == null || Strings.isBlank(employee.getId())) {
                        log.info("EmployeeWriteServiceImpl.importEmployeeHandle:员工创建失败={}", JSONObject.toJSONString(employee));
                        //                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-006", null).getDisplayErrorMessage());
                        employeeRequest.setErrorMessage(employee.getMessage());
                        continue;
                    }
                    log.info("EmployeeWriteServiceImpl.importEmployeeHandle:员工创建成功={}", JSONObject.toJSONString(employee));
                    //员工id
                    employeeRequest.setId(employee.getId());
                    //员工创建成功后发送邮件，没有填写邮箱就跳过
                    try {
                        if (employeeRequest.getEmail() != null && Strings.isNotBlank(employeeRequest.getEmail())) {
                            CreateAccountForTheFirstTimeResponse response = bcOtsService.createAccountForTheFirstTime(CreateAccountForTheFirstTimeRequest.builder()
                                    .title("2").nick(employeeRequest.getNick()).email(employeeRequest.getEmail()).password(OtsPlatformEnhanceConstants.EMPLOYEE_PASSWORD()).build());
                            //邮件发送失败只记录
                            if (!response.getSuccess()) {
                                log.info("员工id："+ employee.getId() + "邮件发送失败：" + response.getMessage());
                                employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-014", null).getDisplayErrorMessage());
                            }
                            log.info("EmployeeWriteServiceImpl.importEmployeeHandle:邮件发送成功={}", JSONObject.toJSONString(response));
                        }
                    } catch (Exception e) {
                        log.info("员工id："+ employee.getId() + "邮件发送服务异常");
                    }
                    //组织下新增员工
                    if (addOrganizationEmployees(employeeRequest, apiContext)) continue;
                } else {
                    //根据账号只能查到一条数据
                    employeeRequest.setId(employeeSDOList.getResult().get(0).getId());
                    //更新必填字段：员工id、组织id
                    Result<Boolean> updateResult = otsPlatformEnhanceService.updateEmployee(UpdateEmployeeRequest.builder()
                            .id(Optional.ofNullable(employeeRequest.getId()).orElse(null))
                            .name(Optional.ofNullable(employeeRequest.getName()).orElse(null))
                            .nick(Optional.ofNullable(employeeRequest.getNick()).orElse(null))
                            .workId(Optional.ofNullable(employeeRequest.getWorkId()).orElse(null))
                            .phone(Optional.ofNullable(employeeRequest.getPhone()).orElse(null))
                            .email(Optional.ofNullable(employeeRequest.getEmail()).orElse(null))
                            .belongOrganizationId(Optional.ofNullable(employeeRequest.getBelongOrganizationId()).orElse(null))
                            .validStartDate(Optional.ofNullable(employeeRequest.getValidStartDate()).orElse(null))
                            .validEndDate(Optional.ofNullable(employeeRequest.getValidEndDate()).orElse(null))
                            .operatorId(Optional.ofNullable(apiContext.getEmployeeId()).orElse(null))
                            .features(Optional.of(JSONObject.toJSONString(featuresMap)).orElse(null))
                            .identityCardNumber(Optional.of(employeeRequest.getIdentityCardNumber()).orElse(null))
                            .build());//更新员工信息
                    if (!updateResult.isSuccess() || !updateResult.getResult()) {
                        log.info("EmployeeWriteServiceImpl.importEmployeeHandle:员工更新失败={}", JSONObject.toJSONString(updateResult));
                        //                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-011", null).getDisplayErrorMessage());
                        employeeRequest.setErrorMessage(updateResult.getMessage());
                        continue;
                    }
                    log.info("EmployeeWriteServiceImpl.importEmployeeHandle:员工更新成功={}", JSONObject.toJSONString(updateResult));
                    //员工关联新的组织，再移除旧的组织
                    Result<List<OrganizationSDO>> employeeOrganizations = otsPlatformEnhanceService.getEmployeeOrganizations(GetEmployeeOrganizationsRequest.builder()
                            .employeeId(Optional.ofNullable(employeeRequest.getId()).orElse(null))
                            .belongOrganizationId(Optional.ofNullable(employeeRequest.getBelongOrganizationId()).orElse(null)).build());
                    log.info("EmployeeWriteServiceImpl.importEmployeeHandle:查询员工组织信息={}", JSONObject.toJSONString(employeeOrganizations));
                    String removeOrganizationId = "";
                    if (CollectionUtils.isNotEmpty(employeeOrganizations.getResult())) {
                        removeOrganizationId = employeeOrganizations.getResult().stream().map(OrganizationSDO::getId).collect(Collectors.toList()).get(0);
                    }
                    //判断新增的组织id和移除的组织id是否相同
                    if (!removeOrganizationId.equals(employeeRequest.getRelationOrganizationId())) {
                        if (addOrganizationEmployees(employeeRequest, apiContext)) continue;
                        //需要移除的组织id为空就跳过移除的操作
                        if (Strings.isNotBlank(removeOrganizationId)) {
                            Result<Boolean> removeResult = otsPlatformEnhanceService.removeOrganizationEmployees(RemoveOrganizationEmployeesRequest.builder()
                                    .bizId(Optional.ofNullable(apiContext.getBizId()).orElse(null))
                                    .bizType(Optional.ofNullable(apiContext.getBizType()).orElse(null))
                                    .operatorId(Optional.ofNullable(apiContext.getEmployeeId()).orElse(null))
                                    .organizationId(Optional.of(removeOrganizationId).orElse(null))
                                    .employeeIds(Optional.of(Lists.newArrayList(employeeRequest.getId())).orElse(null))
                                    .build());
                            if (!removeResult.isSuccess() || !removeResult.getResult()) {
                                log.info("EmployeeWriteServiceImpl.importEmployeeHandle:员工组织删除失败={}", JSONObject.toJSONString(removeResult));
                                //                            employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-010", null).getDisplayErrorMessage());
                                employeeRequest.setErrorMessage(removeResult.getMessage());
                            }
                            log.info("EmployeeWriteServiceImpl.importEmployeeHandle:员工组织删除成功={}", JSONObject.toJSONString(removeResult));
                        }
                    }
                }

                if (Strings.isBlank(employeeRequest.getRoleName())) {
                    continue;
                }
                //根据逗号切割
                List<String> roleNameList = Lists.newArrayList(Arrays.asList(employeeRequest.getRoleName().split("[,，]")));
                log.info("EmployeeWriteServiceImpl.importEmployeeHandle:需要修改的功能角色={}", JSONObject.toJSONString(roleNameList));
                //角色名称转换成id
                Result<List<RoleSDO>> roles = otsPlatformEnhanceService.getRoles(GetRolesRequest.builder().type(1).belongOrganizationId("1").build());
                Map<String, String> roleMap = roles.getResult().stream().collect(Collectors.toMap(RoleSDO::getName, RoleSDO::getId));
                List<String> roleIdList = roleNameList.stream().map(roleMap::get).filter(Strings::isNotBlank).collect(Collectors.toList());
                //需要判断传入的角色名称是否存在，不存在的角色更新以后员工数据会有问题
                if (CollectionUtils.isEmpty(roleIdList)) {
                    employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-012", null).getDisplayErrorMessage());
                    continue;
                }

                //更新角色参照oms的接口
                Result<RoleSDO> roleSDOResult = otsPlatformEnhanceService.getRole(GetRoleRequest.builder()
                        .organizationId(Optional.ofNullable(employeeRequest.getBelongOrganizationId()).orElse(null))
                        .roleId(null).code("administrator").build());//查询角色
                log.info("getPersonInChargeRoleId：所属组织为" + employeeRequest.getBelongOrganizationId() + "的角色的负责人信息为" + JSON
                        .toJSONString(roleSDOResult) + "traceId为" + TraceUtil.getTraceId());
                String personInChargeRoleId = Optional.ofNullable(roleSDOResult)
                        .filter(Result::isSuccess)
                        .map(Result::getResult)
                        .map(RoleSDO::getId)
                        .orElse(null);

                //员工如果还没有分配角色就不需要验证
                if (personInChargeRoleId != null) {
                    // 被编辑员工的角色列表
                    Result<List<RoleSDO>> employeeRoles = otsPlatformEnhanceService.getEmployeeRoles(GetEmployeeRolesRequest.builder()
                            .id(Optional.ofNullable(employeeRequest.getId()).orElse(null)).build());//获取一个员工的所有角色
                    log.info("EmployeeWriteServiceImpl.importEmployeeHandle:获取员工当前的角色={}", JSONObject.toJSONString(employeeRoles));

                    List<RoleSDO> roleSDOList = Optional.ofNullable(employeeRoles)
                            .filter(Result::isSuccess)
                            .map(Result::getResult)
                            .orElse(Collections.emptyList());
                    // 被编辑员工的角色ID列表
                    List<String> existRoleIds = roleSDOList.stream()
                            .filter(roleSDO -> Objects.equals(roleSDO.getType(), 1))
                            .filter(Objects::nonNull)
                            .map(RoleSDO::getId)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());

                    //更新时要把已关联的角色也放进去
    //                roleIdList.addAll(existRoleIds);
    //                roleIdList = roleIdList.stream().distinct().collect(Collectors.toList());
                    // 如果操作的是自己，并且删除了自己的负责人角色，则报错
                    if (Objects.equals(employeeRequest.getId(), apiContext.getEmployeeId())
                            && existRoleIds.contains(personInChargeRoleId)
                            && roleIdList.stream().noneMatch(
                            roleId -> Objects.equals(roleId, personInChargeRoleId))) {
                        employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-007", null).getDisplayErrorMessage());
                        continue;
                    }
                }

                //全量更新一个员工的所有角色
                log.info("EmployeeWriteServiceImpl.importEmployeeHandle:更新员工的角色开始");
                Result<Boolean> editResult = otsPlatformEnhanceService.editEmployeeRoles(EditEmployeeRolesRequest.builder()
                        .employeeId(Optional.ofNullable(employeeRequest.getId()).orElse(null))
                        .belongOrganizationId(Optional.ofNullable(employeeRequest.getBelongOrganizationId()).orElse(null))
                        .roleIds(roleIdList)
                        .operatorId(Optional.ofNullable(apiContext.getEmployeeId()).orElse(null))
                        .build());//更新功能角色
                if (!editResult.isSuccess() || !editResult.getResult()) {
                    log.info("EmployeeWriteServiceImpl.importEmployeeHandle:更新员工的角色失败={}", JSONObject.toJSONString(editResult));
                    //                employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-008", null).getDisplayErrorMessage());
                    employeeRequest.setErrorMessage(editResult.getMessage());
                }
                log.info("EmployeeWriteServiceImpl.importEmployeeHandle:更新员工的角色成功={}", JSONObject.toJSONString(editResult));
            } catch (Exception e) {
                log.error("importEmployeeHandle员工导入服务异常", e);
                employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-024", null).getDisplayErrorMessage());
                continue;
            }
        }
        log.info("EmployeeWriteServiceImpl.importEmployeeHandle:员工导入结束");
        return Result.success(request);
    }

    private Map<String, String> convertFeaturesMap(EmployeeImportRequest employeeRequest) {
        Map<String, String> featuresMap = new HashMap<>();
        if (Strings.isNotBlank(employeeRequest.getCustomerCode())) {
            log.info("EmployeeWriteServiceImpl.importEmployeeHandle:客户编码打标={}", employeeRequest.getCustomerCode());
            BatchQueryCustomers2Response result = otsPlatformEnhanceService.batchQueryCustomers2(BatchQueryCustomers2Request.builder()
                    .codes(Lists.newArrayList(employeeRequest.getCustomerCode())).build());
            if (CollectionUtils.isNotEmpty(result.getResult())) {
                featuresMap.put(CUSTOMER_CODE, employeeRequest.getCustomerCode());
                featuresMap.put(NICK_TYPE, NickTypeEnum.CUSTOMER.getType().toString());
            } else {
                employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-032", null).getDisplayErrorMessage());
//                    continue;
            }
        }
        if (Strings.isNotBlank(employeeRequest.getCustomerAddressCode())) {
            log.info("EmployeeWriteServiceImpl.importEmployeeHandle:送达方编码打标={}", employeeRequest.getCustomerAddressCode());
            Result<List<CustomerAddress>> result = customerAddressService.batchQueryAddressByCondition(BatchQueryAddressByConditionRequest.builder()
                    .addressCodes(Lists.newArrayList(employeeRequest.getCustomerAddressCode())).build());
            if (CollectionUtils.isNotEmpty(result.getResult())) {
                featuresMap.put(CUSTOMER_ADDRESS_CODE, employeeRequest.getCustomerAddressCode());
            } else {
                employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-013", null).getDisplayErrorMessage());
//                    continue;
            }
        }
        if (StringUtils.isNotEmpty(employeeRequest.getSupervisorName())) {
            featuresMap.put(SUPERVISOR_NAME, employeeRequest.getSupervisorName());
        }
        if (StringUtils.isNotEmpty(employeeRequest.getSupervisorWorkId())) {
            featuresMap.put(SUPERVISOR_WORK_ID, employeeRequest.getSupervisorWorkId());
        }
        log.info("EmployeeWriteServiceImpl.importEmployeeHandle:featuresMap={}", JSONObject.toJSONString(featuresMap));
        return MapUtils.isEmpty(featuresMap) ? null : featuresMap;
    }

    /**
     * checkEmployee
     *
     * @param checkEmployeeRequest
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> checkEmployee(CheckEmployeeRequest checkEmployeeRequest) {
        try {
            String employeeId = checkEmployeeRequest.getEmployeeId();
            if (employeeId == null) {
                return Result.success(false, "OTS-01-001-01-16-015", ErrorMessage.code("OTS-01-001-01-16-015", null).getDisplayErrorMessage());
            }
            //分子公司员工编辑选择的组织 不能是上级组织
            EmployeeGetCurrentLoginResponse loginUser = bcOtsService.employeeGetCurrentLogin();
            if(Integer.parseInt(loginUser.getRelatedOrganizationType()) >= OrganizationTypeEnum.COMPANY.getCode()){
                GetTopOrganizationListRequest getTopOrganizationListRequest = new GetTopOrganizationListRequest();
                getTopOrganizationListRequest.setId(loginUser.getRelatedOrganizationId());
                getTopOrganizationListRequest.setType(OrganizationTypeEnum.GROUP.getCode());
                Result<List<TopOrganizationListResponse>> orgListResult = otsPlatformEnhanceService.getTopOrganizationList(getTopOrganizationListRequest);
                List<TopOrganizationListResponse> orgList = orgListResult.getResult();
                orgList.remove(0);
                boolean  b = orgListResult.getResult().stream().anyMatch(x -> x.getId().equals(checkEmployeeRequest.getOrganizationId()));
                if(b){
                    return Result.success(false, "OTS-01-001-01-16-028", ErrorMessage.code("OTS-01-001-01-16-028", null).getDisplayErrorMessage());
                }
            }
            //判断有没有分配为销售负责人
            PageQueryAddressListResponse addressListResponse = otsPlatformEnhanceService.pageQueryAddressList(PageQueryAddressListRequest.builder().principal(employeeId).build());
            if (!addressListResponse.getSuccess()) {
                return Result.success(false, "OTS-01-001-01-16-018", ErrorMessage.code("OTS-01-001-01-16-018", null).getDisplayErrorMessage());
            }
            PageQueryCustomerScopeResponse customerScopeResponse = otsPlatformEnhanceService.pageQueryCustomerScope(PageQueryCustomerScopeRequest.builder().principal(employeeId).build());
            if (!customerScopeResponse.getSuccess()) {
                return Result.success(false, "OTS-01-001-01-16-019", ErrorMessage.code("OTS-01-001-01-16-019", null).getDisplayErrorMessage());
            }
            if (addressListResponse.getSuccess() && addressListResponse.getTotal() == 0 && customerScopeResponse.getSuccess() && customerScopeResponse.getTotal() == 0) {
                return Result.success(true);
            }
            //查询员工所在的组织
            Result<List<OrganizationSDO>> organization = otsPlatformEnhanceService.getEmployeeOrganizations(GetEmployeeOrganizationsRequest.builder()
                    .employeeId(employeeId).belongOrganizationId("1").build());
            if (!organization.isSuccess()) {
                return Result.success(false, "OTS-01-001-01-16-016", ErrorMessage.code("OTS-01-001-01-16-016", null).getDisplayErrorMessage());
            }
            String id = null;
            if (CollectionUtils.isNotEmpty(organization.getResult()) && organization.getResult().get(0).getId() != null) {
                id = organization.getResult().get(0).getId();
            }
            //判断组织id是否有变更，无变更就允许修改
            String organizationId = checkEmployeeRequest.getOrganizationId();
            if (organizationId == null) {
                if (id == null) {
                    return Result.success(true);
                }
            } else {
                if (organizationId.equals(id)) {
                    return Result.success(true);
                }
            }
            return Result.success(false, "OTS-01-001-01-16-017", ErrorMessage.code("OTS-01-001-01-16-017", null).getDisplayErrorMessage());
        } catch (Exception e) {
            log.error("员工编辑时校验销售负责人失败", e);
            return Result.fail(false, "OTS-01-001-01-16-020", ErrorMessage.code("OTS-01-001-01-16-020", null).getDisplayErrorMessage());
        }
    }

    private boolean addOrganizationEmployees(EmployeeImportRequest employeeRequest, ApiContext apiContext) {
        Result<Boolean> addResult = otsPlatformEnhanceService.addOrganizationEmployees(AddOrganizationEmployeesRequest.builder()
                .bizId(Optional.ofNullable(apiContext.getBizId()).orElse(null))
                .bizType(Optional.ofNullable(apiContext.getBizType()).orElse(null))
                .operatorId(Optional.ofNullable(apiContext.getEmployeeId()).orElse(null))
                .organizationId(Optional.ofNullable(employeeRequest.getRelationOrganizationId()).orElse(null))
                .employeeIds(Optional.of(Lists.newArrayList(employeeRequest.getId())).orElse(null))
                .build());
        if (!addResult.isSuccess() || !addResult.getResult()) {
            log.info("EmployeeWriteServiceImpl.importEmployeeHandle:员工关联组织失败={}", JSONObject.toJSONString(addResult));
//            employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-009", null).getDisplayErrorMessage());
            employeeRequest.setErrorMessage(addResult.getMessage());
            return true;
        }
        log.info("EmployeeWriteServiceImpl.importEmployeeHandle:员工关联组织成功={}", JSONObject.toJSONString(addResult));
        return false;
    }

    public static <T extends ImportRequest> List<T> setRequestErrorMessage(List<T> requestList, String errorMessage){
        requestList.forEach(importRequest -> importRequest.setErrorMessage(errorMessage));
        return requestList;
    }

    private static boolean trimBean(Object object) {
        if (null == object) {
            return true;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                if (f.getGenericType().toString().equals("class java.lang.String")) {
                    f.setAccessible(true);
                    String value = (String) f.get(object);
                    if (null == value) {
                        continue;
                    }
                    value = value.trim();
                    f.set(object, value);
                }
            }
        } catch (Exception e) {
            log.error(JSONObject.toJSONString(object) + "导入员工时去除空格报错" + e);
            return false;
        }
        return true;
    }
}
